package com.example.demo.comtroller;

import com.example.demo.model.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

/**
 * @author 郝文雪
 * @date 2022/7/15 14:54
 * @Description Test
 */

@Controller
@RequestMapping("/user")
@ResponseBody//当前方法返回的是一个非静态页面的数据
@Slf4j
public class UserController {
    private final String SESSION_KEY="SESSION_KEY";
    @RequestMapping("/setsess")
    public boolean setSess(HttpServletRequest request){
        boolean result=false;
        try{
            //1.得到session对象
            HttpSession session = request.getSession(true);
            session.setAttribute(SESSION_KEY,"JAVA");
        }catch (Exception e){
            System.out.println("出现了异常"+e.getMessage());
        }
        result=true;
        return result;
    }

    /**
     * session的读取方式1
     * @return
     */
    @RequestMapping("/getsess")
    public String setSession(HttpServletRequest request){
        String result="";
        HttpSession session = request.getSession(false);
        if(session!=null && session.getAttribute(SESSION_KEY)!=null){
            result= (String) session.getAttribute(SESSION_KEY);
        }
        return result;
    }


    /**
     * 获取session的方式2
     * @return
     */
    @RequestMapping("/getsess2")
    public String getSession2(@SessionAttribute(value="SESSION_KEY",required = false) String data){
        return data;
    }

    @RequestMapping("/getua")
    public String getHeader(@RequestHeader("User-Agent") String userAgent){
        return userAgent;
    }

    /**
     * 获取cookie的方法2
     * @param bite
     * @return
     */
    @RequestMapping("/getck2")
    public String getck2(@CookieValue("bite") String bite){
        return bite;
    }

    /**
     * 获取cookie的方法
     * @param request
     */
    @RequestMapping("/getck")
    public void getCookie(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        log.info("cookie length:" + cookies.length);
        Arrays.stream(cookies).forEach(cookie -> {
            log.info(cookie.getName() + "：" + cookie.getValue());
        });
    }

    @Value("${myfile.path}")
    private String filePath;

    /**
     * 上传文件
     * @param username
     * @param file
     * @return
     */
    @RequestMapping("/upfile")
    public boolean upFile(String username, @RequestPart("myfile")MultipartFile file) {
        boolean result=false;
        try {
            String fileType=file.getOriginalFilename();
            fileType=fileType.substring(fileType.lastIndexOf("."));//获取文件后缀
            //文件保存的名称
            String fileName= UUID.randomUUID().toString()+fileType;
            file.transferTo(new File(filePath+fileName));
            result=true;
            log.info(username +": 上传图片成功！");
        } catch (IOException e) {
            System.out.println("图片上传失败");
        }
        return result;
    }

    @RequestMapping("/hero/{name}/{id}")
    public String hero(@PathVariable String name,@PathVariable Integer id){
        return "名称："+name+" id: "+id;
    }

    @RequestMapping("/reg")
    public UserInfo reg(@RequestBody UserInfo userInfo) {
        return userInfo;
    }

    @RequestMapping("/shownumber")
    public String showNumber(Integer num){
        return "数字："+num;
    }

    @RequestMapping("/login2")
    public String login(@RequestParam(value = "username",required = false) String name,String password){
        return "用户名："+name + " 密码："+password;
    }
    @RequestMapping("/login")
    public boolean isLogin(String name,String password){
        boolean result=false;
        if(StringUtils.hasLength(name)  && StringUtils.hasLength(password) && name.equals("admin") &&
        password.equals("admin")){
            result=true;
        }
        return result;
    }


    /**
     * 接收单个参数
     * @param name
     * @return
     */
    @RequestMapping("/showname")
    public String showName(String name){
        return "姓名："+name;
    }
    //表示此方法只支持GET类型的请求
    @RequestMapping(value = "/sayhi",method = RequestMethod.GET) //路由映射（用户和程序的连接）
    public String sayHi(){
        return "Hello,Spring MVC";
    }

    @GetMapping("/sayhi2") //只支持get类型的请求
    public String sayHi2(){
        return "hi,Spring MVC2";
    }

    @PostMapping("/sayhi3")
    public String sayHi3(){
        return "Hello,Spring MVC3";
    }
}
